package 二叉树.平衡二叉树;

import java.util.*;
import java.util.stream.IntStream;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2023/1/30 20:13
 * @description:
 * @version:
 */
public class Solution {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(3,new TreeNode(9),new TreeNode(20,new TreeNode(15),new TreeNode(7)));
        System.out.println(isBalanced(root));
    }

    //错误解法，思路有问题
    public static boolean isBalanced(TreeNode root) {
        //存储叶子节点所在层次
        List<Integer> list = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        if (root == null){
            return true;
        }
        queue.offer(root);
        int level = 1;
        while (!queue.isEmpty()){
            int size = queue.size();
            while (size > 0){
                TreeNode node = queue.poll();
                if ((node.left == null && node.right == null) || (node.left == null || node.right == null)){
                    list.add(level);
                }
                if (node.left != null){
                    queue.offer(node.left);
                }
                if (node.right != null){
                    queue.offer(node.right);
                }
                size--;
            }
            level++;
        }
        //通过list中最大的层次减去最小的层次，来判断该二叉树是否为平衡二叉树
        int[] array = list.stream().mapToInt(Integer::valueOf).toArray();
        Arrays.sort(array);
        int result = array[array.length - 1] - array[0];
        if (result <= 1){
            return true;
        }
        return false;
    }


    //自顶向下递归
    public static boolean isBalanced2(TreeNode root) {
        if (root == null) {
            return true;
        } else {
            return Math.abs(height(root.left) - height(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right);
        }
    }

    //求出当前节点的高度
    public static int height(TreeNode root) {
        if (root == null) {
            return 0;
        } else {
            return Math.max(height(root.left), height(root.right)) + 1;
        }
    }
}
